/*
 * PrimeNumbers.java    1.0 Nov 4, 2013
 *
 * Program should find prime numbers which are smaller or equal to the inputted
 * from keyboard integer number
 */


public class PrimeNumbers {
    public static void main(String[] args){
        int parsedNumber = Commons.getIntWithPrompt(Messages.ENTER_NUMBER);

        if (parsedNumber <= 1) {
            Commons
                .terminateProgramWithMessage(
                        Messages.NUMBER_MUST_BE_GREATER_THAN_ONE);
        }

        int[] primeNumbers = findPrimeNumbers(parsedNumber);
        
        printPrimeNumbersArray(primeNumbers);
    }

    public static void printPrimeNumbersArray(int[] primeNumbers) {
        System.out.print(Messages.PRIME_NUMBERS_ARE);

        boolean isFirstNumberFound = false;
        for (int i : primeNumbers) {
            if (isFirstNumberFound) {
                System.out.print(", ");
            }
            System.out.print(i);
            isFirstNumberFound = true;
        }

        System.out.println(Messages.PRIME_NUMBERS_ARE_CONCLUSION);
    }

    public static int[] findPrimeNumbers(int upperBorder) {
        int[] primeNumbers = {};
        boolean isPrime = true;

        for (int i = 2; i <= upperBorder; i++) {
            isPrime = true; 
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrime = false; 
                    break;
                }
            }
            if (isPrime) {
                primeNumbers = appendIntToArray(i, primeNumbers);
            }
        }

        return primeNumbers;
    }

    public static int[] appendIntToArray(int i, int[] array) {
        int[] result = new int[array.length + 1];

        System.arraycopy(array, 0, result, 0, array.length);
        result[array.length] = i;
        return result;
    }
}
